package cn.stronglink.assetmanage.business.inventory.view.detail;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import Scaner.rfid.IRfidListener;
import Scaner.rfid.TimerRfidScaner;
import Scaner.scan.IScanerListener;
import Scaner.scan.TimerInfraraedScaner;
import cn.stronglink.assetmanage.R;
import cn.stronglink.assetmanage.business.inventory.adapter.InventoryOrderAdapter;
import cn.stronglink.assetmanage.business.inventory.model.InventoryFactory;
import cn.stronglink.assetmanage.dao.DaoManager;
import cn.stronglink.assetmanage.dao.InventoryDao;
import cn.stronglink.assetmanage.dao.InventoryDetailDao;
import cn.stronglink.assetmanage.entity.Inventory;
import cn.stronglink.assetmanage.entity.InventoryDetail;
import cn.stronglink.assetmanage.entity.User;
import cn.stronglink.assetmanage.utils.Constants;
import cn.stronglink.assetmanage.widget.CustomProgressDialog;
import cn.stronglink.assetmanage.widget.ViewPagerFragment;

import static android.R.attr.data;
import static android.R.attr.theme;
import static android.R.attr.thickness;

/**
 * 待入库表单列表
 */
public class InventoryDetailFragment extends ViewPagerFragment implements KeyEvent.Callback {
    private TextView tvInventoryOrderId;   // 盘点单号
    private TextView tvInventoryLocation;   // 盘点位置
    private TextView tvOpreationUser;       // 操作人
    private TextView tvOpreationTime;       // 操作日期
    private Button butSacnQR, butScanRFID;
    private TimerInfraraedScaner scaner;
    private TimerRfidScaner rfidScaner;
    private ExpandableListView rv_inventory_detail_list;

    private List<String> goodsGroupNameList;                // 盘点商品的组名称
    private InventoryOrderAdapter orderAdapter;             // 订单详情的Adapter

    private Inventory inventory;    // 盘点信息实体
    private Map<String, InventoryDetail> planGoodsMap = new HashMap<>();  // 计划盘点的商品列表
    private Map<String, InventoryDetail> inventoryProfitMap = new HashMap<>();  // 盘盈列表
    private Map<String, InventoryDetail> inventoryNormalMap = new HashMap<>();  // 正常盘点到到商品列表

    private InventoryFactory factory = new InventoryFactory();// 盘点用工厂类
    private Dialog mDialog;
    private Context mContext;
    private Activity mactivity;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_inventory_detail, container, false);
        mContext = this.getContext();
        mactivity = this.getActivity();
        try {
            initView(rootView);
            final Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    if (mactivity == null) {
                        mactivity = InventoryDetailFragment.this.getActivity();
                    }
                    mDialog = CustomProgressDialog.createLoadingDialog(mContext, "正在加载中...");
                    mDialog.show();
                    initData();
                    Log.e("代码===", "initData");
                }
            };

            new Thread() {
                public void run() {
                    Looper.prepare();
                    new Handler().post(runnable);
                    Looper.loop();
                }
            }.start();

        } catch (Exception e) {
            Toast.makeText(this.getContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
        }
        return rootView;
    }

    private void initView(View view) {

        if (this.inventory == null) return;
        this.tvInventoryOrderId = view.findViewById(R.id.tv_inventoryuncount_order_name);
        this.tvInventoryOrderId.setText(this.inventory.getId_());
        this.tvInventoryLocation = view.findViewById(R.id.tv_inventory_location);
        this.tvInventoryLocation.setText(this.inventory.getRoomName());
        this.tvOpreationUser = view.findViewById(R.id.tv_inventoryuncount_operation_user);
        this.tvOpreationUser.setText(User.getInstance().getName());
        this.tvOpreationTime = view.findViewById(R.id.tv_inventoryuncount_operation_date);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd-HH:mm:ss");
        this.tvOpreationTime.setText(format.format(new Date()));

        View vBack = this.getActivity().findViewById(R.id.txt_left_title);
        vBack.setVisibility(View.VISIBLE);
        View vSave = this.getActivity().findViewById(R.id.txt_right_title);
        vSave.setVisibility(View.INVISIBLE);

        // 加载资产列表
        this.goodsGroupNameList = new ArrayList<>();
        this.goodsGroupNameList.add(getResources().getString(R.string.inventory_more));
        this.goodsGroupNameList.add(getResources().getString(R.string.inventory_normal));
        this.orderAdapter = new InventoryOrderAdapter(getActivity(), goodsGroupNameList);
        this.rv_inventory_detail_list = view.findViewById(R.id.rv_inventory_detail_list); // 扩展
        this.rv_inventory_detail_list.setAdapter(this.orderAdapter);
        this.loadDataToAdapter();  // 将数据加载到adapter

        // 初始化条码扫描按钮
        this.butSacnQR = view.findViewById(R.id.btn_inventory_detail_qr); // 扫描条码按钮
        this.butSacnQR.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    InventoryDetailFragment.this.scaner.playSingle();
                } catch (Exception e) {
                    Toast.makeText(InventoryDetailFragment.this.getContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }
        });

        // 初始化rfid扫描按钮
        this.butScanRFID = view.findViewById(R.id.btn_inventory_detail_rfid);
        this.butScanRFID.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    InventoryDetailFragment.this.switchRfidScan();
                } catch (Exception e) {
                    Toast.makeText(InventoryDetailFragment.this.getContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }
        });

        // 初始化条码扫描模块
        this.scaner = new TimerInfraraedScaner(this.getContext());
        this.scaner.setScanerListener(new IScanerListener() {
            @Override
            public void onScaning(List<String> data) {
                try {
                    for (int i = 0; i < data.size(); i++) {
                        String rfid = data.get(i).replace(" ", "");
                        InventoryDetailFragment.this.pushRfid(rfid);
                    }
                } catch (Exception e) {
                    Toast.makeText(InventoryDetailFragment.this.getContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }
        });

        // 初始化rfid扫描模块
        this.rfidScaner = new TimerRfidScaner(this.getContext());
        this.rfidScaner.setRfidListener(new IRfidListener() {
            @Override
            public void onRfiding(List<TimerRfidScaner.EpcDataBase> data) {
                try {
                    for (int i = 0; i < data.size(); i++) {
                        String rfid = data.get(i).toString().replace(" ", "");
                        InventoryDetailFragment.this.pushRfid(rfid);
                    }
                } catch (Exception e) {
                    Toast.makeText(InventoryDetailFragment.this.getContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onSet() {

            }

            @Override
            public void getException(String msg) {
                Toast.makeText(InventoryDetailFragment.this.getContext(), msg, Toast.LENGTH_LONG).show();
            }
        });

        // 盘点按钮
        Button butInventoryFinish = view.findViewById(R.id.btn_inventory_detail_finish);
        butInventoryFinish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    InventoryDetailFragment.this.inventory.setStatus(3);
                    InventoryDetailFragment.this.inventory.setUpdateBy(Long.valueOf(User.getInstance().getId_()));

                    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    InventoryDetailFragment.this.inventory.setUpdateTime(format.format(new Date()));
                    InventoryDetailFragment.this.inventory.setExecuteTime(format.format(new Date()));
                    DaoManager
                            .getDaoSession(InventoryDetailFragment.this.getContext()).getInventoryDao().update(InventoryDetailFragment.this.inventory);
                    Toast.makeText(InventoryDetailFragment.this.getContext(),
                            "盘点状态更改完成",
                            Toast.LENGTH_LONG).show();
                    InventoryDetailFragment.this.getActivity().onBackPressed();
                } catch (Exception e) {
                    Toast.makeText(InventoryDetailFragment.this.getContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }
        });

        // 如果盘点单状态为已完成，就屏蔽操作按钮
        if (this.inventory.getStatus() == 3) {
            LinearLayout foot = view.findViewById(R.id.ll_inventoryuncount);
            foot.setVisibility(View.GONE);
        }

        if (mDialog != null) {
            mDialog.cancel();
        }
    }

    /**
     * 初始化数据
     * 资产state状态:1未盘、2差异、3正常、4盘亏、5盘盈
     */
    private void initData() {

        Bundle bundle = getArguments();
        if (bundle == null) {
            Toast.makeText(this.getContext(), "传递的盘点单参数为空，无法正常盘点", Toast.LENGTH_LONG).show();
            return;
        }
        String inventoryOrderId = bundle.getString(Constants.INVENTORY_DETAIL_NO);
        if (inventoryOrderId == null || inventoryOrderId.isEmpty()) {
            Toast.makeText(this.getContext(), "传递的盘点编号为空，无法正常盘点", Toast.LENGTH_LONG).show();
            return;
        }

        // 获取盘点单信息
        this.inventory = DaoManager.getDaoSession(InventoryDetailFragment.this.getContext()).getInventoryDao().queryBuilder().where(
                InventoryDao.Properties.Id_.eq(inventoryOrderId)
        ).unique();

        // 获取盘点中的资产详情
        List<InventoryDetail> detailList = DaoManager.getDaoSession(InventoryDetailFragment.this.getContext()).getInventoryDetailDao().queryBuilder().where(
                InventoryDetailDao.Properties.OrderNo.eq(inventoryOrderId)
        ).list();

        // 将盘点详情遍历到Map中，便于快速查找
        for (int i = 0; i < detailList.size(); i++) {
            InventoryDetail detail = detailList.get(i);

            switch (detail.getStatus()) {
                case 5:
                    inventoryProfitMap.put(detail.getRfidNo(), detail);
                    break;
                case 4:
                    break;
                case 3:
                    inventoryNormalMap.put(detail.getRfidNo(), detail);
                    planGoodsMap.put(detail.getRfidNo(), detail);
                    break;
                case 1:
                    planGoodsMap.put(detail.getRfidNo(), detail);
                    break;
            }

        }

        this.getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {

                initView(rootView);

            }
        });
    }

    /**
     * 加载数据到Adapter中
     */
    private void loadDataToAdapter() {
        ((List<InventoryDetail>) this.orderAdapter.getGroup(0)).addAll(this.inventoryProfitMap.values());
        ((List<InventoryDetail>) this.orderAdapter.getGroup(1)).addAll(this.inventoryNormalMap.values());
        orderAdapter.notifyDataSetChanged();  // 刷新列表
        rv_inventory_detail_list.expandGroup(1);
    }

    /**
     * 开启或关闭rfid扫描
     */
    private void switchRfidScan() {
        if (rfidScaner.isSearching()) {
            rfidScaner.StopSearch();
            butScanRFID.setText("开始扫RFID盘点");

        } else {
            rfidScaner.StartSearch();
            butScanRFID.setText("停止扫RFID盘点");
        }
    }

    /**
     * 推送扫到的Rfid到指定列表
     *
     * @param code
     */
    private void pushRfid(String code) {
        final String rfid = code.replace("\r", "");
        if (planGoodsMap.containsKey(rfid)) {
            // 如果扫到的rfid在盘点计划里，并且没有在已盘到的资产列表里，就添加信息到已盘到的列表中
            if (!inventoryNormalMap.containsKey(rfid)) {
                InventoryDetail goods = planGoodsMap.get(rfid);
                goods.setStatus(3); // 更改资产状态为已盘点
                inventoryNormalMap.put(rfid, goods); // 将新盘到的资产添加到缓存列表中
                DaoManager.getDaoSession(getContext()).getInventoryDetailDao().update(goods); // 将资产保持到数据
                this.getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ((List<InventoryDetail>) orderAdapter.getGroup(1)).add(0, planGoodsMap.get(rfid)); // 向盘点列表中添加资产信息
                        orderAdapter.notifyDataSetChanged(); // 刷新UI
                    }
                });
            }
        } else {
            // 如果扫到的rfid不在盘点计划中，并且没在盘盈列表里，就添加到盘盈列表
            if (!inventoryProfitMap.containsKey(rfid)) {
                final InventoryDetail goods = factory.createInventoryProfitGoods(this.inventory.getId_(), rfid);// 通过工厂创建盘盈资产实例
                inventoryProfitMap.put(rfid, goods);  // 将盘盈资产放到盘盈缓存列表
                DaoManager.getDaoSession(InventoryDetailFragment.this.getContext()).getInventoryDetailDao().insert(goods); // 将资产保持到数据

                // 在界面中显示刚刚盘到的资产
                this.getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ;
                        ((List<InventoryDetail>) orderAdapter.getGroup(0)).add(0, goods); // 向盘盈UI列表中添加资产信息
                        orderAdapter.notifyDataSetChanged();  // 刷新列表
                    }
                });
            }
        }
    }

    /**
     * 退出释放资源
     */
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        try {
            if (this.rfidScaner != null) {
                this.rfidScaner.StopSearch();
                this.rfidScaner.Destory();
            }
        } catch (Exception e) {
            Toast.makeText(this.getContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
        }
        try {
            if (this.scaner != null) {
                this.scaner.stop();
                this.scaner.destory();
            }
        } catch (Exception e) {
            Toast.makeText(this.getContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent keyEvent) {
        try {
            // 按下F3按钮进行Rfid扫描器的开关操作
            if (keyCode == 133) {
                this.switchRfidScan();
            }
        } catch (Exception e) {
            Toast.makeText(this.getContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
        }
        return false;
    }

    @Override
    public boolean onKeyLongPress(int i, KeyEvent keyEvent) {
        return false;
    }

    @Override
    public boolean onKeyUp(int i, KeyEvent keyEvent) {
        return false;
    }

    @Override
    public boolean onKeyMultiple(int i, int i1, KeyEvent keyEvent) {
        return false;
    }
}
